package com.luochen.cdpt.service;

import com.luochen.cdpt.eneity.EmpInfo;
import com.luochen.cdpt.eneity.Page;
import com.luochen.cdpt.response.RespBean;
import com.luochen.cdpt.eneity.User;
import com.luochen.cdpt.repository.IEmpInfoRepository;
import com.luochen.cdpt.repository.IUserRepository;
import com.luochen.cdpt.util.BeanUtils;
import com.luochen.cdpt.util.MD5Util;
import com.luochen.cdpt.util.SqlUtil;
import com.luochen.cdpt.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: star
 * @Date: 2018/12/14 09:19
 * @Description:
 */
@Service
public class EmpService {

    @Autowired
    IEmpInfoRepository empInfoRepository;

    @Autowired
    EntityManager entityManager;

    @Autowired
    IUserRepository userRepository;

    /**
     * 通过条件查询员工列表
     * @param request
     * @return
     */
    public Page<Map> findEmpList(HttpServletRequest request) {
        try {
            String orgcde = request.getParameter("orgcde");//机构代码：
            String tcrttm = request.getParameter("tcrttm");//创建时间：
            String empcde = request.getParameter("empcde");//员工代码：
            String mobilephone = request.getParameter("mobilephone");//手机号码：
            String empname = request.getParameter("empname");//员工名称：
            String status = request.getParameter("status");//状态：
            String teamcde = request.getParameter("teamcde");//团队：
            //分页参数也需要传进来
            String sql = "select new Map(e1.empcde as empcde,e1.id as id," +
                    "  e1.empname as empname," +
                    "  e3.teamcde as teamcde,e3.teamname as teamname," +
                    "  e1.mobilephone as mobilephone,e2.orgcde as orgcde,e2.orgname as orgname,e1.status as status) from EmpInfo e1," +
                    "  OrgInfo e2,TeamInfo e3 where e1.teamid=e3.teamcde" +
                    " and e2.orgcde=e3.orgcde ";
            Map<String, String> sqlMap = new HashMap<>();
            sqlMap.put("e2.orgcde", orgcde);
            sqlMap.put("e1.empcde", empcde);
            sqlMap.put("e1.mobilephone", mobilephone);
            sqlMap.put("e1.status", status);
            sqlMap.put("e3.teamcde", teamcde);
            sql = sql + SqlUtil.bulidSql(sqlMap);
            if (!StringUtils.isEmptry(empname)) {
                sql = sql + " and e1.empname like '%" + empname + "%'";
            }
            if (!StringUtils.isEmptry(tcrttm)) {
                sql = sql + " and date_format(e1.tcrttm,'%Y-%m-%d') =:tcrttm";
            }
            sql = sql +" Order By e1.tcrttm desc ";
            Query query = entityManager.createQuery(sql);
            int totalCount = query.getResultList().size();
            if (!StringUtils.isEmptry(tcrttm)) {
                query.setParameter("tcrttm", tcrttm);
            }
            SqlUtil.setPageParam(request, query);
            List<Map> list = query.getResultList();
            return Page.of(totalCount, list);
        }catch (Exception e){
            e.printStackTrace();
            return Page.error("查询失败");
        }

    }

    /**
     * 保存、更新
     * @param empInfo
     * @return
     */
    @Transactional
    public RespBean save(EmpInfo empInfo) {
        try {
            EmpInfo empInfo1;
            Long id = empInfo.getId();
            if (null != id) {
                empInfo1 = empInfoRepository.findById(id).get();
                BeanUtils.copyPropertiesNotNull(empInfo1, empInfo);
            } else {
                empInfo1 = empInfo;
            }
            empInfoRepository.save(empInfo1);
            //新增员工时，登录用户表也新增一条数据
            User user1 = userRepository.findByUsername(empInfo.getEmpcde());
            if(user1==null){
                User user = new User();
                user.setUsername(empInfo.getEmpcde());
                user.setPassword(MD5Util.encode("888888"));
                String status = empInfo1.getStatus();
                if("1".equals(status)){
                    user.setEnabled(true);
                }else {
                    user.setEnabled(false);
                }
                userRepository.save(user);
            }else{
                //如果员工离职，则登录表user状态也修改
                String status = empInfo1.getStatus();
                if("0".endsWith(status)){
                    user1.setEnabled(false);
                    userRepository.save(user1);
                }
            }
            return RespBean.ok("保存成功", empInfo1);
        } catch (Exception e) {
            return RespBean.error("保存失败");
        }
    }
}
